import { useRequest } from 'ahooks'
import { Pagination, Spin, Table, Typography } from 'antd'
import React, { useState } from 'react'
import { useParams } from 'react-router-dom'
import { STAT_PAGE_SIZE } from '../../../constant'
import useGetComponentInfo from '../../../hooks/useGetComponentInfo'
import { getQuestionStatListService } from '../../../services/stat'

interface PropsType {
  selectedComponentId: string
  setSelectedComponentId: (id: string) => void
  setSelectedComponentType: (id: string) => void
}

const PageStat: React.FC<PropsType> = ({
  selectedComponentId,
  setSelectedComponentId,
  setSelectedComponentType,
}) => {
  const { id = '' } = useParams()
  const [total, setTotal] = useState(0)
  const [list, setList] = useState([])
  const { componentList } = useGetComponentInfo()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(STAT_PAGE_SIZE)

  const { loading } = useRequest(
    async () =>
      await getQuestionStatListService(id, {
        page,
        pageSize,
      }),
    {
      refreshDeps: [page, pageSize, id],
      onSuccess: res => {
        const { total = 0, list = [] } = res
        setTotal(total)
        setList(list)
      },
    }
  )

  const columns = componentList.map(({ fe_id, title, props, type }) => {
    const colTitle = props!.title || title

    return {
      // title: props!.title || title,
      title: (
        <div
          style={{ cursor: 'pointer' }}
          onClick={() => {
            setSelectedComponentId(fe_id)
            setSelectedComponentType(type)
          }}
        >
          <span style={{ color: fe_id === selectedComponentId ? '#1890ff' : '' }}>{colTitle}</span>
        </div>
      ),
      dataIndex: fe_id,
    }
  })

  const TableElem = (
    <>
      <Table
        columns={columns}
        dataSource={list.map((item: any) => ({ ...item, key: item._id }))}
        pagination={false}
      ></Table>
      <div style={{ textAlign: 'center', marginTop: '18px' }}>
        <Pagination
          total={total}
          pageSize={pageSize}
          current={page}
          onChange={page => setPage(page)}
          onShowSizeChange={(page, pageSize) => {
            setPage(page)
            setPageSize(pageSize)
          }}
        />
      </div>
    </>
  )

  return (
    <div>
      <Typography.Title level={3}>答卷数量: {!loading && total}</Typography.Title>
      {loading && (
        <div style={{ textAlign: 'center' }}>
          <Spin></Spin>
        </div>
      )}
      {!loading && TableElem}
    </div>
  )
}

export default PageStat
